package com.sunshine.lnuplus.ui.fragment

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.Service
import android.content.*
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.lifecycle.ViewModelProvider
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseFragment
import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.LessonBean
import com.sunshine.lnuplus.model.room.CountDown
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.service.LoadWeatherService
import com.sunshine.lnuplus.ui.activity.*
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.LessonUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.utils.UpdateWidgetUtils
import com.sunshine.lnuplus.view.DialogWithoutView
import com.sunshine.lnuplus.view.LoginDialog
import com.sunshine.lnuplus.view.ScrollTextView
import com.sunshine.lnuplus.viewModel.MeViewModel
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.fragment_today.*
import org.apache.log4j.chainsaw.Main
import java.util.*
import kotlin.Exception
import kotlin.collections.ArrayList

/**
 * Created by sunshine on 2020/4/10
 */
class TodayFragment : BaseFragment() {

    private var todayLesson = ArrayList<LessonBean>()
    private var thisWeek = 1
    private var countDownList: List<CountDown>? = null
    private var conn: ServiceConnection? = null
    private var getLastUpdateWeatherTime: SharedPreferences? = null
    private lateinit var viewModel: MeViewModel

    override fun setContent(): Int {
        return R.layout.fragment_today
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_today, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this).get(MeViewModel::class.java)
        initView()
    }

    private fun initView() {
        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        setHasOptionsMenu(true)
        if(getTimetableTheme() == 1 && !context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)){
            textView_date.setTextColor(Color.BLACK)
            textView_timetable.setTextColor(Color.BLACK)
            textView_count_down.setTextColor(Color.BLACK)
            iv_wea.setImageDrawable(resources.getDrawable(R.drawable.ic_wea_black))
            iv_timetable.setImageDrawable(resources.getDrawable(R.drawable.ic_timetable_black))
            iv_countdown.setImageDrawable(resources.getDrawable(R.drawable.ic_count_down_black))
            iv_function.setImageDrawable(resources.getDrawable(R.drawable.ic_function_black))
            toolbar_layout.setCollapsedTitleTextColor(Color.BLACK)
        }
        thisWeek = DateUtils.getThisWeek(InitData.lessonStyle.startMonth, InitData.lessonStyle.startDay)
        todayLesson.clear()
        if(InitData.lessonStyle.nextDay && InitData.lessonStyle.nextDayTime <= DateUtils.hour){
            InitData.lessonList!!.forEach {
                var nextDay = DateUtils.getTodayOfWeek() + 1
                var nextWeek = thisWeek
                if (DateUtils.getTodayOfWeek() == 7){
                    nextDay = 1
                    nextWeek++
                }
                if(it.dayOfWeek == nextDay && it.weeks.contains(nextWeek)){
                    todayLesson.add(it)
                }
            }
        }else{
            InitData.lessonList!!.forEach {
                if(it.dayOfWeek == DateUtils.getTodayOfWeek() && it.weeks.contains(thisWeek)){
                    todayLesson.add(it)
                }
            }
        }

        Collections.sort(todayLesson, LessonComparable())
        countDownList = TimetableRepository(context!!).getTodayCountDown()
        initHead()
        initWeather()
        initTimetable()
        initCountDown()
        initFunction()
    }

    private fun initHead() {
        toolbar_layout.setExpandedTitleColor(Color.TRANSPARENT)
        val hour = DateUtils.hour
        var titleString = ""
        var lessonString = if(todayLesson.size ==0) "今天没有课噢，" else "今天有${todayLesson.size}节课，"
        if (InitData.lessonStyle.nextDay && InitData.lessonStyle.nextDayTime <= DateUtils.hour) {
            lessonString = lessonString.replace("今", "明")
        }
        when (hour) {
            in 5..8 -> {
                toolbar.title = "没有清晨会被辜负"
                titleString = "早上好 "
            }
            in 9..11 -> {
                toolbar.title = "开启充实的一天吧"
                titleString = "上午好 "
            }
            in 12..17 -> {
                toolbar.title = "午后时光也不要浪费"
                titleString = "下午好 "
            }
            in 18..22 -> {
                toolbar.title = "美好的一天结束啦"
                titleString = "晚上好 "
            }
            else -> {
                toolbar.title = "不要熬夜 早些休息"
                titleString = "快去睡觉 "
            }
        }
        titleString += "今天是${DateUtils.month}月${DateUtils.day}日 周${DateUtils.getTodayOfWeekString(DateUtils.getTodayOfWeek())}"
        textView_date.text = titleString

        lessonString += when (todayLesson.size){
            0 -> "好好休息一下吧"
            1,2 -> "坚持一下"
            else -> "加油加油"
        }
        textView_timetable.text = lessonString

        if(countDownList != null && countDownList!!.isNotEmpty()){
            textView_count_down.text = "今天有${countDownList!!.size}件事情，不要忘记噢"
        }
    }

    private fun initWeather(){
        getLastUpdateWeatherTime = context?.getSharedPreferences("weather", Context.MODE_PRIVATE)
        val timeDifference: Long
        val lastDay: Int = getLastUpdateWeatherTime!!.getInt("lastDay", 0)
        val lastHour: Int = getLastUpdateWeatherTime!!.getInt("lastHour", 0)
        val lastMinute: Int = getLastUpdateWeatherTime!!.getInt("lastMinute", 0)
        timeDifference = (DateUtils.day - lastDay) * 1440 + (DateUtils.hour - lastHour) * 60 + (DateUtils.minute - lastMinute).toLong()
        if (timeDifference > 240) {
            val intent = Intent(activity, LoadWeatherService::class.java)
            var loadWeatherService: LoadWeatherService

            conn = object : ServiceConnection {
                override fun onServiceDisconnected(name: ComponentName) {}
                override fun onServiceConnected(
                    name: ComponentName,
                    service: IBinder
                ) {
                    loadWeatherService = (service as LoadWeatherService.MyBind).getService()
                    loadWeatherService.setCallBack(
                        object : LoadDataCallBack {
                            override fun onSuccess() {
                                handler.sendEmptyMessage(1)
                            }
                        })
                }
            }
            activity?.bindService(intent, conn!!, Service.BIND_AUTO_CREATE)
        }else{
            handler.sendEmptyMessage(1)
        }
    }

    private fun initTimetable() {
        ll_timetable2.removeAllViews()
        var titleText = "第${thisWeek}周 周${DateUtils.getTodayOfWeekString(DateUtils.getTodayOfWeek())}"
        if (InitData.lessonStyle.nextDay && InitData.lessonStyle.nextDayTime <= DateUtils.hour) titleText += " 以下是明日课程"
        textView_timetable_title.text = titleText
        if(todayLesson.size > 0){
            ll_timetable.removeView(textView_timetable_empty)
            todayLesson.forEach {
                val view = LayoutInflater.from(context!!).inflate(R.layout.item_day, ll_timetable, false)
                val cardView = view.findViewById<CardView>(R.id.day_cardview)
                val time = view.findViewById<TextView>(R.id.time)
                val lessonName = view.findViewById<ScrollTextView>(R.id.lesson_name)
                val info = view.findViewById<ScrollTextView>(R.id.info)
                cardView.setCardBackgroundColor(Color.TRANSPARENT)
                cardView.setOnClickListener {
                    (activity as MainActivity).setCurrentItem(1)
                    (activity as MainActivity).showBNB()
                }
                time.setTextColor(Color.BLACK)
                time.text = "第${it.start}节\n第${it.end}节"
                lessonName.setTextColor(Color.BLACK)
                lessonName.text = it.lessonName
                info.setTextColor(Color.BLACK)
                info.text = "地点：${it.location} 老师：${it.teacher}"

                ll_timetable2.addView(view)
            }
        }
    }

    private fun initCountDown(){
        ll_countdown2.removeAllViews()
        if(countDownList!=null && countDownList!!.isNotEmpty()){
            ll_countdown.removeView(textView_countdown_empty)
            countDownList!!.forEach {
                val view = LayoutInflater.from(context!!).inflate(R.layout.item_day, ll_timetable, false)
                val cardView = view.findViewById<CardView>(R.id.day_cardview)
                cardView.setOnClickListener {
                    (activity as MainActivity).setCurrentItem(2)
                    (activity as MainActivity).showBNB()
                }
                val time = view.findViewById<TextView>(R.id.time)
                val lessonName = view.findViewById<ScrollTextView>(R.id.lesson_name)
                val info = view.findViewById<ScrollTextView>(R.id.info)
                cardView.setCardBackgroundColor(Color.TRANSPARENT)
                time.setTextColor(Color.BLACK)
                val minute: String = if(it.minute < 10) "0${it.minute}" else it.minute.toString()
                time.text = "今天\n${it.hour}:$minute"
                lessonName.setTextColor(Color.BLACK)
                lessonName.text = it.lessonName
                info.setTextColor(Color.BLACK)
                info.text = "地点：${it.location}"

                ll_countdown2.addView(view)
            }
        }
    }

    private fun initFunction(){
        mb_shipei.setOnClickListener {
            DialogWithoutView.newInstance(
                "申请适配",
                resources.getString(R.string.shipei),
                true,
                null,
                null
            ).show(childFragmentManager, "")
        }
        mb_appsetting.setOnClickListener {
            activity?.startActivityForResult(Intent(activity, AppSettingActivity::class.java), TagHelper.MAIN)
        }
        mb_giveme.setOnClickListener {
            DialogWithoutView.newInstance("感谢你",
                resources.getString(R.string.thank_you),
                true,
                null,
                null
            ).show(childFragmentManager, "help_me")
        }
        mb_timetablesetting.setOnClickListener {
            startActivityForResult(Intent(activity, TimetableSettingActivity::class.java), TagHelper.TODAY)
        }
        mb_widgetsetting.setOnClickListener {
            startActivity(Intent(activity, WidgetSettingActivity::class.java))
        }
        mb_calender.setOnClickListener {
            startActivity(Intent(activity, CalenderActivity::class.java))
        }
        mb_b_and_r.setOnClickListener {
            startActivityForResult(Intent(activity, BandRActivity::class.java), TagHelper.TODAY)
        }
        mb_help.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("title","反馈")
            bundle.putString("url","https://support.qq.com/product/131050")
            startActivity(Intent(activity, WebViewActivity::class.java).putExtras(bundle))
        }
        mb_about.setOnClickListener {
            startActivity(Intent(activity, AboutActivity::class.java))
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.today_menu, menu)
        if(getTimetableTheme() == 1 && !context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).getBoolean("night", false)){
            menu.getItem(0).icon = resources.getDrawable(R.drawable.ic_me_black)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.user -> {
                val loginDialog = LoginDialog.newInstance(this, TagHelper.TODAY)
                loginDialog.show(childFragmentManager, "login")
            }
        }
        return true
    }

    @SuppressLint("HandlerLeak")
    val handler = object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                1 -> {
                    textView_wea_title.text = "${getLastUpdateWeatherTime!!.getString("city", "城市")}"
                    textView_tem.text = "${getLastUpdateWeatherTime!!.getString("tem", "18")}°"
                    textView_wea.text = "${getLastUpdateWeatherTime!!.getString("weather", "晴")}"
                    textView_air.text = "空气质量 ${getLastUpdateWeatherTime!!.getString("air", "50")}"
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.TODAY){
            when(resultCode){
                TagHelper.TIMETABLESETTING -> (activity as MainActivity).getTimetableAdapter()?.notifyDataSetChanged()
                TagHelper.LOGIN, TagHelper.BANDRR -> {
                    DialogWithoutView.newInstance(
                        "提示",
                        "刚刚导入课程，默认的开学时间是每年3月/9月的第一个星期一，是否要更改一下呢",
                        false,
                        DialogInterface.OnClickListener { _, _ ->
                            val sp = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE)
                            val edit = sp.edit()
                            val month = sp.getInt("start_month", if(DateUtils.month > 8) 8 else 2)
                            val day = sp.getInt("start_day", 1)
                            val datePickerDialog = DatePickerDialog(context!!,
                                DatePickerDialog.OnDateSetListener { _, _, month, dayOfMonth ->

                                    edit.apply{
                                        putInt("start_month", month)
                                        putInt("start_day", dayOfMonth)
                                        apply()
                                    }
                                    InitData.lessonStyle.startMonth = month
                                    InitData.lessonStyle.startDay = dayOfMonth
                                    initView()
                                    (activity as MainActivity).getTimetableAdapter()?.notifyDataSetChanged()
                                    Toasty.success(context!!, "设置成功~").show()
                                    activity?.startActivity(Intent(activity, (activity as MainActivity).javaClass))
                                    activity?.finish()
                                }, DateUtils.year, month, day
                            )
                            datePickerDialog.show()
                        },
                        DialogInterface.OnClickListener { _, _ ->
                            activity?.startActivity(Intent(activity, (activity as MainActivity).javaClass))
                            activity?.finish()
                        }
                    ).show(childFragmentManager, "")
                    LessonUtils.initLessonBean(
                        viewModel.getAllLesson(),
                        context!!,
                        childFragmentManager,
                        viewModel.repository
                    )

                    UpdateWidgetUtils.updateWidgets(context!!)
                    (activity as MainActivity).getTimetableAdapter()?.notifyDataSetChanged()
                    Toasty.success(context!!, resources.getString(R.string.jiexi_success), Toasty.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(conn != null){
            try {
                activity?.unbindService(conn!!)
            }catch (e: Exception){}

        }
    }

    /**
     * fragment可见时刷新界面
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        try {
            if(userVisibleHint){
                initView()
            }
        }catch (e: Exception){}
    }

    override fun onResume() {
        super.onResume()
        initView()
    }
}

class LessonComparable : Comparator<LessonBean>{
    override fun compare(o1: LessonBean?, o2: LessonBean?): Int {
        return o1!!.start.compareTo(o2!!.start)
    }

}